package com.github.codemperor.core.schedule;

import com.alibaba.fastjson.JSONObject;
import com.github.codemperor.core.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.Map;

/**
 * 初始化所有的job
 * 在调用方加入下面这行，初始化bean即可
 */
@Slf4j
public class EmScheduleDispatch implements SchedulingConfigurer {
    private int poolSize = 50;
    private String threadNamePrefix = "EmTask-";
    private int awaitTerminationSeconds = 60;

    public EmScheduleDispatch() {
    }

    public EmScheduleDispatch(int poolSize, String threadNamePrefix, int awaitTerminationSeconds) {
        this.poolSize = poolSize;
        this.threadNamePrefix = threadNamePrefix;
        this.awaitTerminationSeconds = awaitTerminationSeconds;
    }

    /**
     * 异步配置
     *
     * @return
     */
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.initialize();
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.setThreadNamePrefix(threadNamePrefix);
        //调度器shutdown被调用时等待当前被调度的任务完成
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //等待时长
        taskScheduler.setAwaitTerminationSeconds(awaitTerminationSeconds);
        return taskScheduler;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Map<String, BaseEmScheduler> schedulerMap = SpringContextUtil.getApplicationContext().getBeansOfType(BaseEmScheduler.class);
        if (schedulerMap.isEmpty()) {
            return;
        }
        //这里方法可以自实现
        schedulerMap.forEach((key, scheduler) -> {
            scheduler.init();
            Runnable task = scheduler.getTask();
            Trigger trigger = scheduler.getTrigger();
            if (task == null || trigger == null) {
                log.warn("[EmScheduleDispatch] config: {}, task or trigger is null", JSONObject.toJSONString(scheduler.config()));
                return;
            }
            scheduledTaskRegistrar.addTriggerTask(task, trigger);
        });
    }
}
